-- index+search lua-l

search = {}

search.build_index = function()
	local threads, err = db.execute"SELECT M.ThreadID, T.Title, M.Message FROM Thread T INNER JOIN Message M ON T.MessageID = M.ThreadID"
	if err then
		print(err)
		return false
	end
	
	local thread = {}
	
	while threads:fetch(thread, "a") do
		search.index_thread(thread, conn)
		
	end	

end


search.index_thread = function(t, conn)

	local message = t.Message
	for word in message:gmatch("%w+") do 
		word = string.lower(word)
		if word ~= '' then
			local _, err = db.execute("insert into Term(ThreadID, Term) VALUES ('" .. t.ThreadID .. "', '" .. word .. "')"..
				    "on duplicate key update Frequency = Frequency + 1")
			if err then 
				print(err) 
				return
			end
		end
	end
end


search.query = function(terms)
	local q = [[
	SELECT TH.MessageID, TH.Title, TH.Date 
	FROM Thread TH ]]
	local count = 1
	
	local order = {}
	
	for word in terms:gmatch("[%w-]+") do
		q = q .. "\nINNER JOIN Term T"..count..[[
		ON TH.MessageID = T]]..count..[[.ThreadID
		AND T]]..count..[[.Term = ']]..word.."'"
		
		table.insert(order, 'T'..count..'.Ranking')
		
		count = count + 1
	end
	
	q = q.."\nORDER BY ".. table.concat(order, " + ") .. " LIMIT 0, 100"


	return db.execute(q)
end